package com.starblink.mine.personhome.ui.follow.ui

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.tabs.TabLayout
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.ApolloModelExt.isFansOpen
import com.starblink.android.basic.ext.ApolloModelExt.isFollowOpen
import com.starblink.android.basic.ext.bindFragment
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.modules.mine.MineManager.FollowPageTabType.TAB_FOLLOWERS
import com.starblink.android.basic.modules.mine.MineManager.FollowPageTabType.TAB_FOLLOWING
import com.starblink.android.basic.widget.edittext.textChangeFlow
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.mine.R
import com.starblink.mine.databinding.ActivityFollowBinding
import com.starblink.mine.personhome.ui.follow.ui.followlist.ui.FollowListFragment
import com.starblink.mine.personhome.ui.widget.TabViewHolder
import com.starblink.rocketreserver.fragment.AccountF
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * 关注页面
 * @note 主态关注页面、客态关注页面复用同一页面
 * 主态关注页面：搜索+我关注的用户列表+我的粉丝列表
 * 客态关注页面：客态用户关注的用户列表+客态用户的粉丝列表
 */
@Route(path = RoutePage.Mine.FOLLOW, extras = RoutePage.Extra.NEED_LOGIN)
class FollowActivity : BaseTVMActivity<ActivityFollowBinding, FollowVM>() {
    private val sharedViewModel by viewModels<SharedSearchViewModel>()

    @Autowired(name = MineManager.KEY_PAGE_TYPE)
    @JvmField
    var pageType: Int = MineManager.PersonHomePageType.MINE

    @Autowired(name = MineManager.KEY_TAB_TYPE)
    @JvmField
    var tabType: Int = TAB_FOLLOWING

    // 仅客态时传入
    @Autowired(name = MineManager.KEY_ACCOUNT)
    @JvmField
    var accountF: AccountF? = null

    override fun initViewBinding(): ActivityFollowBinding =
        ActivityFollowBinding.inflate(layoutInflater)

    override fun initData() {
        super.initData()
    }

    override fun initView() {
        super.initView()
        // 初始化标题栏
        viewBinding.titleBar.setTitle(
            if (pageType == MineManager.PersonHomePageType.MINE) {
                UserDataCenter.getAccountInfo()?.username
                    ?: UserDataCenter.getAccountInfo()?.userName ?: ""
            } else {
                accountF?.username ?: accountF?.userName ?: ""
            }
        )
        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })

        initSearchBar()
        initViewPagerAndTabLayout()
    }

    // 初始化搜索栏
    fun initSearchBar() {
        // 仅我的关注，显示搜索
        if (pageType == MineManager.PersonHomePageType.OTHER_USER) {
            viewBinding.laySearch.visibleOrGone(false)
            return
        }

        viewBinding.tvCancel.click {
            viewBinding.etSearch.clearEditFocus()
            viewBinding.etSearch.text = ""
            viewBinding.tvCancel.visibleOrGone(false)
        }
        viewBinding.etSearch.setOnEditFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                //获取焦点
                YYLogUtils.e("search获取焦点", "dss")
                viewBinding.tvCancel.visibleOrGone(true)
            } else {
                //失去焦点
                YYLogUtils.e("search失去焦点", "dss")
            }
        }
        lifecycleScope.launch {
            viewBinding.etSearch.textChangeFlow()
                .debounce(300)
                .onEach {
                    YYLogUtils.e(
                        "Activity onEach key=$it in thread${Thread.currentThread().name}",
                        "dss"
                    )
                    if (viewBinding.viewPager.currentItem == TAB_FOLLOWING) {
                        sharedViewModel.sendSearchEventForFollowingList(it)
                    } else {
                        sharedViewModel.sendSearchEventForFollowerList(it)
                    }
                }.collect()
        }
    }

    val pageTitle = mutableListOf("Following", "Followers")

    fun initViewPagerAndTabLayout() {
        viewBinding.viewPager.bindFragment(
            supportFragmentManager, pageTitles = pageTitle, count = pageTitle.size
        ) {
            when (it) {
                TAB_FOLLOWING -> {
                    // 关注列表
                    if (pageType == MineManager.PersonHomePageType.MINE) {
                        FollowListFragment.newInstance(
                            FollowListFragment.PAGE_TYPE_FOLLOWING,
                            UserDataCenter.getAccountInfo()?.id ?: "",
                        )
                    } else {
                        FollowListFragment.newInstance(
                            FollowListFragment.PAGE_TYPE_FOLLOWING,
                            accountF!!.id,
                            accountF!!.isFollowOpen()
                        )
                    }
                }
                else -> {
                    // 粉丝列表
                    if (pageType == MineManager.PersonHomePageType.MINE) {
                        FollowListFragment.newInstance(
                            FollowListFragment.PAGE_TYPE_FOLLOWERS,
                            UserDataCenter.getAccountInfo()?.id ?: "",
                        )
                    } else {
                        FollowListFragment.newInstance(
                            FollowListFragment.PAGE_TYPE_FOLLOWERS,
                            accountF!!.id,
                            accountF!!.isFansOpen()
                        )
                    }
                }
            }
        }

        //tabLayout关联viewpager
        viewBinding.tabLayout.setupWithViewPager(viewBinding.viewPager)
        initTabView()

        if (pageType == MineManager.PersonHomePageType.MINE) {
            // 仅我的关注，显示搜索
            viewBinding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageScrollStateChanged(state: Int) {}

                override fun onPageSelected(position: Int) {
                    viewBinding.etSearch.setHint(
                        if (position == TAB_FOLLOWING) {
                            "Search for people you follow"
                        } else {
                            "Search your followers"
                        }
                    )
                    if (viewBinding.tvCancel.visibility == View.VISIBLE) {
                        viewBinding.tvCancel.performClick()
                    }
                    // 切换页面后，将原页面搜索列表关闭（如果存在的话）
                    if (position == TAB_FOLLOWING) {
                        sharedViewModel.sendSearchEventForFollowerList("")
                    } else {
                        sharedViewModel.sendSearchEventForFollowingList("")
                    }
                }
            })
        } else {
            // 仅其他用户关注，显示不允许查看
            if (!accountF!!.isFollowOpen()) {
                tabVH = TabViewHolder(viewBinding.tabLayout.getTabAt(TAB_FOLLOWING)!!.customView!!)
                tabVH!!.ivIcon.visibleOrGone(true)
            }
            if (!accountF!!.isFansOpen()) {
                tabVH = TabViewHolder(viewBinding.tabLayout.getTabAt(TAB_FOLLOWERS)!!.customView!!)
                tabVH!!.ivIcon.visibleOrGone(true)
            }
        }

        // 设置默认选中TAB
        viewBinding.tabLayout.getTabAt(tabType)?.select()
    }

    private var tabVH: TabViewHolder? = null
    private fun initTabView() {
        tabVH = null
        for (i in 0 until viewBinding.tabLayout.tabCount) {
            val tab = viewBinding.tabLayout.getTabAt(i)
            //给tab设置自定义布局
            tab!!.setCustomView(R.layout.tab_item_person_home)
            tabVH = TabViewHolder(tab.customView!!)
            //填充数据
            tabVH!!.tvName.text = pageTitle[i]
            //设置默认选择UI
            if (i == tabType) {
                tabVH!!.setTabSelectedStyle()
            }
        }
        viewBinding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                // 设置选中样式
                TabViewHolder(tab.customView!!).setTabSelectedStyle()
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                // 设置默认样式
                TabViewHolder(tab.customView!!).setTabUnselectedStyle()
            }

            override fun onTabReselected(tab: TabLayout.Tab) {}
        })
    }

    override fun initLoad() {
        super.initLoad()
    }
}